<?php
class NotificationsController extends AppController {
    public $helpers = array('Html', 'Form','Session');
    public $components = array('Session','Auth');
    public $uses=array('Notification','Order','User');
    public function index(){
      $userid= $this->Auth->User('id');
      $this->set('title_for_layout', 'История оповещений');
      $this->set('user_name_sidebar', AppController::getUserName($userid));
      $this->paginate = array(
        'limit' => 15,
        'order' => array(
            'Notification.id' => 'desc'
        ),
        'conditions' => array('Notification.userid =' =>$userid ),
        'conditions' =>  array (
          'OR' => array(
              array('Notification.userid =' =>$userid ),
              array('Notification.circle =' => 'public'),
          )
        )
      );
      $notifications=$this->paginate('Notification');
      $this->set('notifications',$notifications);
    }
    public function admin(){
      $userid= $this->Auth->User('id');
      if(AppController::isAuthorized($userid)){
        $this->set('title_for_layout', 'Создать новое оповещение');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
        if ($this->request->is('post')) { //admin send
        $this->request->data['Notification']['time']=time();
        $this->request->data['Notification']['onmain']=1;
        if($this->request->data['Notification']['type']==0)
            $this->request->data['Notification']['type']='grey';
        else
            $this->request->data['Notification']['type']='red';
        if($this->request->data['Notification']['circle']==0)
        {
          $this->request->data['Notification']['circle']='public';
          $this->request->data['Notification']['userid']=0;
          $this->request->data['Notification']['orderid']=0;
        }
        else
        {
          $this->request->data['Notification']['circle']='private';
          //Если это личное уведомление, то надо проверить, не указан ли какой-либо сервер в поле ордерайди
          if(!is_numeric($this->request->data['Notification']['orderid']))
          {
            //надо отыскать айди юзера из заказа, который расположен на сервере
            $server_ip=$this->request->data['Notification']['orderid'];
            $orders=$this->Order->findAllByServerip($server_ip);
            foreach($orders as $order)
            {
              $uid=$order['Order']['userid'];
              $this->request->data['Notification']['userid']=$uid;
              $this->request->data['Notification']['orderid']=$order['Order']['id'];
              $userdata=$this->User->findById($uid);
              $email=$userdata['User']['email'];
              $this->Notification->create();
              if ($this->Notification->save($this->request->data)) {
                //Отправляем письмо юзеру на емаил
                $headers= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=utf-8\r\n";
                $headers.="From: notification@radioheart.ru\r\n";
                $message=$this->request->data['Notification']['text'];
                //mail($email, "RadioHeart.ru: ".$this->request->data['Notification']['title'],$message,$headers);
                $tmp=AppController::send_email($email, "RadioHeart.ru: ".$this->request->data['Notification']['title'],$message,$headers);
              }
            }
            /*echo '<pre>';
            print_r($this->request->data['Notification']);
            echo '</pre>';*/
            $this->Session->setFlash(__('Уведомления успешно созданы и отправлены всем пользователям сервера '.$server_ip));
            $this->redirect(array('action' => 'admin'));
          }
        }
        $this->Notification->create();
        if ($this->Notification->save($this->request->data)) {
          $this->Session->setFlash(__('Уведомление успешно создано'));
          $this->redirect(array('action' => 'admin'));
        }
            echo '<pre>';
            print_r($this->request->data['Notification']);
            echo '</pre>';
        }
        else //showform
        {}
      }
      else
      {
        $this->redirect(array('action' => 'index'));
      }
    }

}


?>